package com.example.s07upload.conctroller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @author: lazyfier
 * @create 2022-04-04 22:27
 */
@Controller
public class UploadController {

    final static String UPLOADED_FOLDER = "./upload/";

    @RequestMapping("/")
    public String index()
    {
        return "upload";
    }

    @RequestMapping("/uploadStatus")
    public String uploadStatus()
    {
        return "status";
    }

    // RedirectAttributes redirectAttributes 将信息传递给跳转的页面
    // Controller 传递参数 可以哦那它

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes)
    {

        byte[] bytes = new byte[0];
        try {
            bytes = file.getBytes();
            // UPLOADED_FOLDER 文件本地存储地址
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            // 写入文件
            Files.write(path, bytes);

            // 参数传递
//            redirectAttributes.addAttribute("message","上传成功");
            redirectAttributes.addFlashAttribute("message","上传成功");
        } catch (IOException e)
        {
//            redirectAttributes.addAttribute("message","上传失败:"+e.getMessage());
            redirectAttributes.addFlashAttribute("message","上传失败:"+e.getMessage());
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }


    @GetMapping("/uploadMore")
    public String uploadMore() {
        return "uploadMore";
    }

    @PostMapping("/uploadMore")
    public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
                                 RedirectAttributes redirectAttributes) {
        if (files.length==0)
        {
            redirectAttributes.addFlashAttribute("message", "请选择至少一个文件");
            return "redirect:uploadStatus";
        }
        for(MultipartFile file:files){
            try {
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        redirectAttributes.addFlashAttribute("message", "上传成功");
        return "redirect:/uploadStatus";
    }
}
